package lumis.portal.presentation.perspective.admin;

import java.util.List;

import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.presentation.tag.page.RenderHolderComponent;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.util.XmlUtil;

import org.apache.wicket.Component.IVisitor;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.IHeaderResponse;

/**
 * Behavior that provides the javascript for processing the save of the
 * layout of a page.
 *
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
@SuppressWarnings("serial")
public class SaveHoldersLayoutBehavior extends AbstractDefaultAjaxBehavior
{
	@Override
	protected void respond(final AjaxRequestTarget target)
	{
		final StringBuilder layoutXml = new StringBuilder(500);
		
		layoutXml.append("<layout>");
		
		// for each RenderHolderComponent
		LayoutFilePage layoutFilePage = (LayoutFilePage) getComponent();
		layoutFilePage.visitChildren(RenderHolderComponent.class, new IVisitor<RenderHolderComponent>()
		{
			public Object component(RenderHolderComponent component)
			{
				// append the xml for the holder
				List<String> serviceInterfaceInstanceIds = component.getServiceInterfaceInstanceIds();
				if (!serviceInterfaceInstanceIds.isEmpty())
				{
					layoutXml.append("<holder id=\"" + XmlUtil.encodeXml(component.getHolderId()) + "\">");
					for (String interfaceInstanceId: serviceInterfaceInstanceIds)
					{
						layoutXml.append("<interface id=\"" + interfaceInstanceId + "\"/>");
					}
					layoutXml.append("</holder>");
				}
				
				return CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
			}
		});
		
		layoutXml.append("</layout>");
		
		// update the page layout
		try
		{
			ITransaction transaction = PortalTransactionFactory.createTransaction();
			try
			{
				transaction.begin();
				
				ManagerFactory.getPageManager().updateLayout(
						SessionConfig.getCurrentSessionConfig(), 
						layoutFilePage.getPageWebResource().getPage().getId(), 
						layoutXml.toString(), transaction);
				
				transaction.commit();
			}
			finally
			{
				transaction.dispose();
			}
		}
		catch (PortalException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void renderHead(IHeaderResponse response)
	{
		response.renderJavascript("function savePageHoldersLayout()" +
				"{" +
					"wicketAjaxGet('lumis/portal/presentation/layoutfile/" + getCallbackUrl() + 
					"',function(){LumisPortal.onRefresh()}.bind(this),function(){}.bind(this),function(){return true;}.bind(this));" +
				"}", null);
	}
}